<script setup lang="ts">
import TaskRelationChart from '@/components/TaskRelationChart/TaskRelationChart.vue'
import { useTokenStore } from '@/stores/token/token.store'
import { ElInput, ElLoading, ElMessage } from 'element-plus'
import { nextTick, ref, computed } from 'vue'
import 'element-plus/theme-chalk/el-input.css'
import { TaskService } from '@/services/bussiness/Task/task.service'
import { ApiGetDagErrorResponseDto } from '@/services/bussiness/Task/task.api.dto'
import { useDagStore } from '@/stores/dag/dag.store'
import { useHomeFormStore } from '@/stores/home/form.store'

const dagStore = useDagStore()
const tokenStore = useTokenStore()
const homeFormStore = useHomeFormStore()
const tokenValue = ref(tokenStore.token)

function onTokenInput(value: string) {
  tokenStore.updateToken(value)
}

const dagNameListData = ['daily_dag', 'test']
const dagNameList = ref(dagNameListData)
const currentDagName = ref(dagNameListData[0] || '')

function onCurrentDagChange(dagName: string) {
  currentDagName.value = dagName
}

// 添加标签相关逻辑
const addInputVisible = ref(false)
const addInputValue = ref('')
const addInputRef = ref<InstanceType<typeof ElInput>>()

function handleInputConfirm() {
  if (addInputValue.value === '') {
    addInputVisible.value = false
    return
  }
  if (dagNameList.value.includes(addInputValue.value)) {
    ElMessage({
      type: 'warning',
      message: '名称已存在'
    })
    return
  }
  dagNameList.value.push(addInputValue.value)
  currentDagName.value = addInputValue.value
  addInputVisible.value = false
}

function openInput() {
  addInputVisible.value = true
  nextTick(() => {
    addInputRef.value?.input?.focus()
  })
}

function onSaveBtnClick() {
  if (dagStore.dagChart) {
    TaskService.saveOperateStack()
  }
}

function onChartInit(error: ApiGetDagErrorResponseDto | void) {
  if (error) {
    console.log('error', error)
  } else {
    initDagExecutionHistorySelectOptions()
  }
}

const dagExecutionId = ref('')
let dagExecutionOptions: any = ref([])

async function initDagExecutionHistorySelectOptions() {
  dagExecutionId.value = ''
  homeFormStore.updateDagExecutionId('')
  if (dagStore.dagChart) {
    const response = await TaskService.getDagExecutionHistory(dagStore.dagChart.dagId)

    if (Array.isArray(response)) {
      dagExecutionOptions.value = response
    } else {
      dagExecutionOptions.value = []
    }
  }
}

async function onDagExecutionIdChange(value: string) {
  homeFormStore.updateDagExecutionId(value)
  if (dagStore.dagChart) {
    if (value) {
      // 选中
      const loading = ElLoading.service()
      const response = await TaskService.getLatestTaskHistory(value)
      loading.close()
      if (Array.isArray(response) && response.length > 0) {
        dagStore.dagChart.setNodeStatus(response)
      }
    } else {
      // 清空
      dagStore.dagChart.clearNodeStatus()
    }
  }
}

const currentTaskName = computed(() => {
  if (dagStore.dagChart) {
    return dagStore.dagChart.getTaskNameByTaskId(homeFormStore.currentTaskId)
  }
  return ''
})

function onDagLogFileChange(value: string) {
  changeDagLogFile(value)
}

function changeDagLogFile(value: string) {
  homeFormStore.updateCurrentDagLogFile(value)
}

// 检查按钮
async function onCheckBtnClick() {
  if (dagStore.dagChart) {
    dagExecutionId.value = ''
    const loading = ElLoading.service()
    const response = await TaskService.getRegisterXxlJobList()
    loading.close()
    if (Array.isArray(response?.data)) {
      dagStore.dagChart.setNodeRegisterStatus(response.data)
    } else {
      ElMessage({
        type: 'warning',
        message: response?.msg || '获取已注册taskName列表失败'
      })
    }
  }
}
</script>

<template>
  <el-container class="p-wrapper">
    <el-main>
      <TaskRelationChart :dag-name="currentDagName" @onAfterInit="onChartInit" />
    </el-main>
    <el-aside width="500px" class="side">
      <div class="side-block">
        <div class="side-block-label">token：</div>
        <el-input v-model="tokenValue" @input="onTokenInput" placeholder="token" />
      </div>
      <div class="side-block">
        <div class="side-block-label">dagName：</div>
        <div>
          <el-check-tag
            style="margin-right: 8px"
            v-for="item in dagNameList"
            :key="item"
            :checked="currentDagName === item"
            @change="onCurrentDagChange(item)"
            >{{ item }}</el-check-tag
          >
          <el-input
            v-if="addInputVisible"
            ref="addInputRef"
            class="ml-1 w-20"
            size="small"
            v-model="addInputValue"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag ml-1" size="small" @click="openInput">
            + add
          </el-button>
        </div>
      </div>
      <div class="side-block" v-if="dagExecutionOptions">
        <div class="side-block-label">历史执行状态：</div>
        <el-select
          v-model="dagExecutionId"
          filterable
          placeholder="dagExecutionId"
          clearable
          style="width: 100%"
          @change="onDagExecutionIdChange"
        >
          <el-option
            v-for="item in dagExecutionOptions"
            :key="item.value"
            :value="item.dagExecutionId"
          >
            <div style="line-height: 20px; padding: 10px 0">
              <p>{{ item.dagExecutionId }}</p>
              <p style="color: #999; font-size: 12px">{{ item.startTime }} - {{ item.endTime }}</p>
            </div>
          </el-option>
        </el-select>
      </div>
      <div class="side-block" v-if="homeFormStore.dagLog">
        <div class="side-block-label">【{{ currentTaskName }}】执行log：</div>
        <el-select
          v-model="homeFormStore.currentDagLogFile"
          filterable
          placeholder="dagLogFile"
          style="width: 100%"
          @change="onDagLogFileChange"
        >
          <el-option v-for="item in homeFormStore.dagLog" :key="item" :label="item" :value="item" />
        </el-select>
        <embed
          style="width: 100%; height: 500px"
          :src="homeFormStore.currentDagLogFile"
          type="text/plain"
        />
        <!-- <DagLogTable :filePath="homeFormStore.currentDagLogFile" /> -->
        <!-- <el-table
          :data="homeFormStore.dagLog.fileNameList"
          stripe
          style="width: 100%; margin-bottom: 20px"
          max-height="400px"
        >
          <el-table-column prop="value" label="fileNameList" />
        </el-table>
        <el-table
          :data="homeFormStore.dagLog.fileText"
          stripe
          style="width: 100%"
          max-height="400px"
        >
          <el-table-column prop="value" label="fileText" />
        </el-table> -->
      </div>
      <div class="side-block">
        <el-button type="primary" style="width: 100%" @click="onCheckBtnClick"
          >检查注册状态</el-button
        >
      </div>
    </el-aside>
  </el-container>
</template>

<style scoped>
.p-wrapper {
  width: 100vw;
  height: 100vh;
}

.side {
  background: rgba(0, 0, 0, 0.02);
  padding: 16px;
}

.side-block {
  margin-bottom: 16px;
}

.side-block-label {
  margin-bottom: 5px;
}
</style>

<style>
.el-select-dropdown__item {
  height: auto;
}
</style>
